import os
import shutil
def create_dir_if_not_exists(directory):
    if not os.path.exists(directory):
        os.mkdir(directory)

def classify_images_by_label(root_dir, dict):
    for subdir, dirs, files in os.walk(root_dir):
        for file in files:
            label = file.split('_')[0]
            label = dict[str(label)]
            label_dir = os.path.join(subdir,label)
            create_dir_if_not_exists(label_dir)
            source_path = os.path.join(subdir, file)
            dest_path = os.path.join(label_dir, file)
            shutil.move(source_path, dest_path)

if __name__=='__main__':
    toolboxpath = r'D:\Project_mb\CWTImages\BCI42a'
    # toolboxpath = r'D:\Project_mb\data\BCI42a'
    dict = {'0': 'left_hand', '1':'right_hand', '2':'foot', '3':'tongue'}
    classify_images_by_label(toolboxpath, dict)
